package com.untour.im.nacos.utils;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;

import java.net.InetAddress;
import java.util.Properties;

public class NacosUtil {

    /**
     * 将Netty服务注册进Nacos
     *
     * @param serverName 服务名称
     * @param serverPort 服务端口号
     */
    public static void registerNamingService(String serverName, Integer serverPort, NacosDiscoveryProperties nacosDiscoveryProperties) {
        try {
            Properties properties = new Properties();
            properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosDiscoveryProperties.getServerAddr());
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosDiscoveryProperties.getNamespace());
            NamingService namingService = NamingFactory.createNamingService(properties);
            InetAddress address = InetAddress.getLocalHost();
            namingService.registerInstance(serverName, address.getHostAddress(), serverPort);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
